package com.sq.partner.manager.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.DeptDto;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.TradNotice;
import com.sq.partner.manager.mybatis.model.TradNoticePartner;
import com.sq.partner.manager.mybatis.model.TreeDto;
import com.sq.partner.manager.service.ITradNoticeService;
import com.sq.partner.manager.util.JsonUtils;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;

/**
 * 
 * @author guozizhou 广播信息配置2015-10-22 09:57:58
 */
@Controller
@RequestMapping(value = "/tradNoticeMtInfo")
public class TradNoticeController {
	private static Logger logger = LogUtil.getLog(TradNoticeController.class);
	@Resource
	private ITradNoticeService tradNoticeService;
	
	@RequestMapping(value = "/tradNoticeMtConfig")
	public String tradNoticeMtConfig(ModelMap model) throws Exception {
		List<DictDto> statusLs = DictCache.getDict(Constants.DICT_NOTICE_STATUS_OPTIONS);
		List<DictDto> noticeTypeLs = DictCache.getDict(Constants.DICT_NOTICE_TYPE_OPTIONS);
		List<DictDto> priLs = DictCache.getDict(Constants.DICT_NOTICE_PRI_OPTIONS);
		model.put("noticeTypeLs", noticeTypeLs);
		model.put("statusLs", statusLs);
		model.put("priLs", priLs);
		return "tradNotice/tradNoticeMtConfig";
	}

	@RequestMapping(value = "/queryByCriteria", method = RequestMethod.POST)
	@ResponseBody
	public Page<TradNotice> queryInfoByCriteria(HttpSession session,TradNotice tradNotice,Integer pageIndex) throws Exception {
		Page<TradNotice> page = new Page<TradNotice>();
		page.setCurrent(pageIndex);
		page.setType(tradNotice);
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		logger.debug("---come here tradNotice successful");
		return tradNoticeService.queryInfoByCriteria(page,user);
	}
	
	@RequestMapping(value = "/queryByTradNoticeId", method = RequestMethod.POST)
	@ResponseBody
	public String queryByTradNoticeId(String id) throws Exception {
		TradNotice tn = tradNoticeService.queryInfoByTradNoticeId(id);
		return JsonUtils.toJson(tn);
	}
	
	@RequestMapping(value = "/getPrivilegeBranchInfoListTree", method = RequestMethod.POST)
	public @ResponseBody List<TreeDto> queryChannelInfoListTree(HttpSession session) throws Exception{
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		if(StrUtil.isEmpty(user.getDepartmentStr())){
			return null;
		}
		List<TradNoticePartner> list = null;
		if(user.getDepartmentStr().contains(Constants.HQ_BRANCH_CODE)){
			list = tradNoticeService.queryTreeDtoByPriBranchCode(null);
		}else{
			String deptStr="";
			for(DeptDto tem : user.getDepts()){
				if(2==tem.getDeptCode().length()){
					deptStr +="'"+tem.getDeptCode()+"',";
				}
			}
			list = tradNoticeService.queryTreeDtoByPriBranchCode(deptStr);
		}
		 List<TreeDto> treeList = new ArrayList<TreeDto>();
		 for(TradNoticePartner dbTree : list){
		        TreeDto td = new TreeDto();
		        td.setName(dbTree.getDeptCname());
		        td.setId(dbTree.getDeptCode());
		        td.setpId(dbTree.getSnrDept());
		        treeList.add(td);
		 }
		return treeList;
	}
	@RequestMapping(value = "/queryAllRelationForCurNoticeId", method = RequestMethod.POST)
	public @ResponseBody List<TradNoticePartner> queryAllRelationForCurNoticeId(String noticeId) throws Exception{
		if(StrUtil.isEmpty(noticeId)){
			return null;
		}
		List<TradNoticePartner> list = tradNoticeService.queryRelationInfoByNoticeId(noticeId);
		return list;
	}
	@RequestMapping(value = "/saveOrUpdateTradNoticeMtInfo", method = RequestMethod.POST)
	@ResponseBody
	public Result saveOrUpdateTradNoticeMtInfo(HttpSession session,TradNotice tradNotice,String branchIdStr) throws Exception {
		if(null == tradNotice){
			return Result.error("参数错误,请稍后重试");
		}else if(StrUtil.isEmpty(tradNotice.getTitle())){
			return Result.error("请输入信息标题");
		}else if(StrUtil.isEmpty(tradNotice.getContent())){
			return Result.error("请输入信息内容");
		}else if(tradNotice.getContent().length()>500){
			return Result.error("信息内容字段超长，支持最多500汉字，请检查");
		}else if(null == tradNotice.getPri()){
			return Result.error("优先级不能为空");
		}else if(StrUtil.isEmpty(tradNotice.getStartTimeStr())){
			return Result.error("广播开始时间不能为空");
		}else if(StrUtil.isEmpty(tradNotice.getEndTimeStr())){
			return Result.error("广播结束时间不能为空");
		}else if(StrUtil.isEmpty(tradNotice.getNoticeType())){
			return Result.error("通知类型不能为空");
		}else if(StrUtil.isEmpty(branchIdStr) && "1".equals(tradNotice.getNoticeType())){
			return Result.error("至少选择一个指定机构,请选择");
		}
		//2.add
		tradNotice.setCreateTime(new Date());
		tradNotice.setUpdateTime(new Date());
		tradNotice.setStatus(tradNotice.getStatus());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		tradNotice.setStartTime(sdf.parse(tradNotice.getStartTimeStr()));
		tradNotice.setEndTime(sdf.parse(tradNotice.getEndTimeStr()));
		if(tradNotice.getStartTime().compareTo(tradNotice.getEndTime())>0){
			return Result.error("广播结束时间不能小于广播开始时间");
		}
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		tradNotice.setOperUser(String.valueOf(user.getUserid()));
		if(StrUtil.isNotEmpty(tradNotice.getId())){
			//1.delete
			tradNoticeService.delTradNoticePartnerById(tradNotice.getId());
			tradNoticeService.delTradNoticeById(tradNotice.getId());
		}
		String returnKeyId = tradNoticeService.addTradNoticeInfo(tradNotice);
		List<TradNoticePartner> list = new ArrayList<TradNoticePartner>();//关联关系
		//按照通知类型处理
		if(StrUtil.isEmpty(user.getDepartmentStr())){
			return Result.error("添加失败，用户权限不足！");
		}else if(user.getDepartmentStr().contains(Constants.HQ_BRANCH_CODE)){
			 if("0".equals(tradNotice.getNoticeType())){
				 TradNoticePartner hq = new TradNoticePartner();
				 hq.setNoticeId(returnKeyId);
				 hq.setDeptNo("00");
				 list.add(hq);
			 }else if("1".equals(tradNotice.getNoticeType())){
				 String dpsArr[] = branchIdStr.split(",");
				 for(int i=0;i<dpsArr.length;i++){
					 TradNoticePartner tnp = new TradNoticePartner();
					 tnp.setNoticeId(returnKeyId);
					 if(!dpsArr[i].contains("~")){
						 tnp.setDeptNo(dpsArr[i]);
					 }else if(dpsArr[i].indexOf("~") == dpsArr[i].lastIndexOf("~")){
						 String channelArr[] = dpsArr[i].split("~");
						 tnp.setPartnerNo(channelArr[0]);
						 tnp.setDeptNo(channelArr[1]);
					 }else if(dpsArr[i].indexOf("~") != dpsArr[i].lastIndexOf("~")){
						 String channelSubArr[] = dpsArr[i].split("~");
						 tnp.setPartnerSaleNo(channelSubArr[0]);
						 tnp.setPartnerNo(channelSubArr[1]);
						 tnp.setDeptNo(channelSubArr[2]);
					 }
					 list.add(tnp);
					}
			 }
		}else{
			if("0".equals(tradNotice.getNoticeType())){
				for(DeptDto tem : user.getDepts()){
					if(2==tem.getDeptCode().length()){
						TradNoticePartner branch = new TradNoticePartner();
						branch.setNoticeId(returnKeyId);
						branch.setDeptNo(tem.getDeptCode());
						list.add(branch);
					}
				}
			 }else if("1".equals(tradNotice.getNoticeType())){
				 String dpsArr_[] = branchIdStr.split(",");
				 for(int i=0;i<dpsArr_.length;i++){
					 TradNoticePartner tnp_ = new TradNoticePartner();
					 tnp_.setNoticeId(returnKeyId);
					 if(!dpsArr_[i].contains("~")){//hq
						 tnp_.setDeptNo(dpsArr_[i]);
					 }else if(dpsArr_[i].indexOf("~") == dpsArr_[i].lastIndexOf("~")){//channel
						 String channelArr_[] = dpsArr_[i].split("~");
						 tnp_.setPartnerNo(channelArr_[0]);
						 tnp_.setDeptNo(channelArr_[1]);
					 }else if(dpsArr_[i].indexOf("~") != dpsArr_[i].lastIndexOf("~")){//subChannel
						 String channelSubArr_[] = dpsArr_[i].split("~");
						 tnp_.setPartnerSaleNo(channelSubArr_[0]);
						 tnp_.setPartnerNo(channelSubArr_[1]);
						 tnp_.setDeptNo(channelSubArr_[2]);
					 }
					 list.add(tnp_);
					}
			 }
		}
		boolean flag  = tradNoticeService.addTradNoticePartnerInfo(list);
		if(flag){
			return Result.success("添加成功！");
		}else{
			return Result.error("添加失败！");
		}
	}
	@RequestMapping(value = "/delTradNoticeMtInfoById", method = RequestMethod.POST)
	@ResponseBody
	public Result delTradNoticeMtInfoById(String id) throws Exception {
		if(StrUtil.isEmpty(id)){
			return Result.error("操作失败，参数错误，请稍后重试！");
		}
		//1.delete
		boolean flag_gx = tradNoticeService.delTradNoticePartnerById(id);
		boolean flag = tradNoticeService.delTradNoticeById(id);
		if(flag_gx & flag)
		{
			return Result.success("删除成功！");
		}
		return Result.error("删除失败！");
	}
	
}
